//
//  WBMainViewController.swift
//  新浪微博
//
//  Created by ZTE on 2017/12/1.
//  Copyright © 2017年 ZTE. All rights reserved.
//

import UIKit
///主控制器
class WBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        setUpChildControllers()
        setUpComposeButton()
    }
    
    //portrait 竖屏
    //控制设备的方向
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        
        return .portrait
    }
    

    //MARK: -监听方法
    //撰写微博
    //FIXME: 没有实现
    //private 能够保证方法私有，仅在当前对象被访问
    //@objc 允许这个函数在“运行时” 通过 OC 的消息机制被调用
    @objc private func composeStatus() {
        
        print("撰写微博")

    }
    
    
    //MARK: - 私有控件
    private lazy var composeButton: UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")

}


//extension 类似于 OC中的分类，在swift中还可以用来切分代码块
//可以把相近功能的函数，放在一个 extension中
//便于代码维护
//注意：和OC 的分类一样， extension中不能定义属性 只能定义方法

//MARK: - 设置界面

extension WBMainViewController {
    
    
    //设置撰写按钮
    private func setUpComposeButton() {
        tabBar.addSubview(composeButton)
        
        //计算按钮的宽度
        let count = CGFloat(childViewControllers.count)
        let w = tabBar.bounds.width / count - 1
        
        composeButton.frame = tabBar.bounds.insetBy(dx: 2 * w, dy: 0)
        
        //按钮监听方法
        composeButton.addTarget(self, action: #selector(composeStatus), for: .touchUpInside)
        
        
    }
    
    //设置所有的子控制器
    private func setUpChildControllers() {
        
        //从 bundle 加载配置的 json
        //1.路径 2.加载NSData 3.反序列化转换成数组
        guard let path = Bundle.main.path(forResource: "main.json", ofType: nil),
            let data = NSData(contentsOfFile: path),
            let array = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [[String : AnyObject]]
        else {
            
            return
        }
        
        //测试数据格式是否正确
      //  (array as NSArray).write(toFile: "/Users/ZTE/Desktop/demo.plist", atomically: true)
        
        //数组 -> json序列化
        //let data = try? JSONSerialization.data(withJSONObject: array, options:[.prettyPrinted])
        //(data! as NSData).write(toFile: "/Users/ZTE/Desktop/main.json", atomically: true)
        
        var arrayM = [UIViewController]()
        
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        
        viewControllers = arrayM
    }
    
    //使用字典创建一个子控制器
    //-parameter dict:信息字典[clsName,title,imageName]
    private func controller(dict:[String:AnyObject]) -> UIViewController {
        
        //1.取得字典内容
        
        guard let clsName = dict["clsName"] as? String,
              let title = dict["title"] as? String,
              let imageName = dict["imageName"] as? String,
              let cls = NSClassFromString(Bundle.main.nameSpace() + "." + clsName) as? WBBaseViewController.Type,
              let visitorDict = dict["visitorInfo"] as? [String:String]
            
        else {
                
                return UIViewController()
        }
        
        //2.创建视图控制器
        let vc = cls.init()
        vc.title = title
        
        //设置控制器的访客信息
        vc.visitorInfoDict = visitorDict
        
        //3.设置图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        //4.设置 tabbar 的标题字体
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.orange], for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedStringKey.font : UIFont.systemFont(ofSize: 12)], for: UIControlState(rawValue:0))
        let nav = WBNavigationController(rootViewController: vc)
        
        return nav
  
    }
    
}
